#include <stdio.h>

void toBoolString(char arg)
{
	int i;
	arg = arg>>1;
	for(i=0;i<4;i++)
		printf("%d",(unsigned)(unsigned char)(0x01&(arg>>i)));
	printf(" ");
	for(;i<7;i++)
		printf("%d",(unsigned)(unsigned char)(0x01&(arg>>i)));
}

int main(int argc, char ** argv )
{
	FILE * input;
	int first;
	char	data,
			ack;
	enum{
		ADDR,
		DATA,
	}expect;

	printf("Run with %d arguments.\n",argc);
	if(argc<2)
		return 1;
	else
		printf("Using %s for input.\n",argv[1]);

	input = fopen(argv[1],"rb");
	expect = ADDR;

	if(input==NULL)
	{
		printf("Unable to open input file.\n");
		return 1;
	}

	first = fgetc(input);
	while( first != EOF )
	{
		switch(first)
		{
			case 'R':
				printf("\nStart condition.\n");
				expect = ADDR;
				break;
			case 'P':
				printf("Stop bit.\n");
				break;
			case 'H':
				data = fgetc(input);
				ack = fgetc(input);
				if(data=='\r'&&ack=='\n')
				{
					data= '\n';
					ack = fgetc(input);
				}
				if(expect==ADDR)
					printf("Address ");
				else
					printf("Data    ");

				printf("0x%.2X",(unsigned)(unsigned char)data);


				if(ack=='A')
				{
					printf(" ACK");
				}
				else if(ack=='N')
				{
					printf(" NACK");
				}
				else
				{
					if( data =='\r' )
						printf("Out of sequence H 0x%.2X(\\r)",(unsigned)(unsigned char)data);
					else if( data == '\n' )
						printf("Out of sequence H 0x%.2X(\\n)",(unsigned)(unsigned char)data);
					else
						printf("Out of sequence H 0x%.2X(%c)",(unsigned)(unsigned char)data,(unsigned)(unsigned char)data);

					if( ack == '\r' )
						printf(" 0x%.2X(\\r)",(unsigned)(unsigned char)ack);
					else if ( ack == '\n' )
						printf(" 0x%.2X(\\n)",(unsigned)(unsigned char)ack);
					else
						printf(" 0x%.2X(%c)",(unsigned)(unsigned char)ack,(unsigned)(unsigned char)ack);
				}
				if(expect=ADDR)
				{
					if( (unsigned)(unsigned char)data&0x01 )
						printf(" (Read  ");
					else
						printf(" (Write ");

					toBoolString(data);
					printf(" )\n");
				}
				else
					printf("\n");

				expect = DATA;
				break;
			default:
				printf("Out of place character 0x%.2X(%c).\n",(unsigned)(unsigned char)first,(unsigned)(unsigned char)first);
		}
		first = fgetc(input);
	}
}
